package com.ruoyi.customer.service.impl;

import java.util.List;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.customer.domain.CsContract;
import com.ruoyi.system.service.ISysRoleService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.customer.mapper.CsCustomerMapper;
import com.ruoyi.customer.domain.CsCustomer;
import com.ruoyi.customer.service.ICsCustomerService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.validation.Validator;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.bean.BeanValidators;

/**
 * 客户Service业务层处理
 *
 * @author 李守壮
 * @date 2023-03-16
 */
@Service
public class CsCustomerServiceImpl implements ICsCustomerService {

    private static final Logger log = LoggerFactory.getLogger(CsCustomerServiceImpl.class);

    @Autowired
    protected Validator validator;

    @Autowired
    private CsCustomerMapper csCustomerMapper;

    @Autowired
    private ISysRoleService sysRoleService;

    /**
     * 查询客户
     *
     * @param id 客户主键
     * @return 客户
     */
    @Override
    public CsCustomer selectCsCustomerById(Long id) {
        return csCustomerMapper.selectCsCustomerById(id);
    }

    /**
     * 查询客户列表
     *
     * @param csCustomer 客户
     * @return 客户
     */
    @Override
    public List<CsCustomer> selectCsCustomerList(CsCustomer csCustomer) {
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        //获取用户角色
        List<Long> roleList= sysRoleService.selectRoleListByUserId(userId);
        csCustomer.setIsDeleted(0);
        if (roleList.size()==1 && roleList.get(0)==5){ //一个角色且是员工staff，那么就只能看自己创建的合同
            csCustomer.setCreateBy(SecurityUtils.getLoginUserIdTypeString());
        }
        return csCustomerMapper.selectCsCustomerList(csCustomer);
    }

    /**
     * 新增客户
     *
     * @param csCustomer 客户
     * @return 结果
     */
    @Override
    public int insertCsCustomer(CsCustomer csCustomer) {
        CsCustomer customerQuery = new CsCustomer();
        customerQuery.setTelephone(csCustomer.getTelephone());
        List<CsCustomer> csCustomers = selectCsCustomerList(customerQuery);
        if (ObjectUtils.isNotEmpty(csCustomers)) {
            CsCustomer selectedCustomer = csCustomers.get(0);
            BeanUtils.copyProperties(csCustomer,selectedCustomer);
            return csCustomerMapper.updateCsCustomer(selectedCustomer);
        }

        String code = "ZJCS"+DateUtils.getTimestampNow();
        csCustomer.setCompanyCode(code);

        csCustomer.setCreateBy(SecurityUtils.getLoginUserIdTypeString());
        return csCustomerMapper.insertCsCustomer(csCustomer);
    }

    /**
     * 修改客户
     *
     * @param csCustomer 客户
     * @return 结果
     */
    @Override
    public int updateCsCustomer(CsCustomer csCustomer) {
        csCustomer.setUpdateBy(SecurityUtils.getLoginUserIdTypeString());
        csCustomer.setUpdateTime(DateUtils.getNowDate());
        return csCustomerMapper.updateCsCustomer(csCustomer);
    }

    /**
     * 批量删除客户
     *
     * @param ids 需要删除的客户主键
     * @return 结果
     */
    @Override
    public int deleteCsCustomerByIds(Long[] ids) {
        for(Long id: ids){
            CsCustomer obj = new CsCustomer();
            obj.setId(id);
            obj.setIsDeleted(2);
            obj.setUpdateTime(DateUtils.getNowDate());
            obj.setUpdateBy(SecurityUtils.getLoginUserIdTypeString());
            csCustomerMapper.updateCsCustomer(obj);
        }
        return 1;

    }

    /**
     * 删除客户信息
     *
     * @param id 客户主键
     * @return 结果
     */
    @Override
    public int deleteCsCustomerById(Long id) {
        return csCustomerMapper.deleteCsCustomerById(id);
    }


    /**
     * 导入数据
     */
    @Override
    public String importData(List<CsCustomer> list, Boolean isUpdateSupport, String operName) {
        if (ObjectUtils.isEmpty(list)) {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (CsCustomer record : list) {
            try {
                // 验证是否存在客户名称
                String companyName =record.getCompanyName();
                if (companyName == null || companyName.equals("")){
                    String msg = "<br/> 没有客户名称会报错的， 导入失败：";
                    failureMsg.append(msg);
                }
                CsCustomer u = getByCompanyName(companyName);
                if (StringUtils.isNull(u)) {
                    BeanValidators.validateWithException(validator, record);
                    this.fastInsertCsCustomer(record);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、客户名称： " + record.getCompanyName() + " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, record);
                    record.setIsDeleted(0);
                    this.updateCsCustomer(record);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、客户名称： " + record.getCompanyName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、客户名称： " + record.getCompanyName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、客户名称： " + record.getCompanyName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public CsCustomer getByPhone(String phone) {

        CsCustomer csCustomer = new CsCustomer();
        csCustomer.setTelephone(phone);
        List<CsCustomer> csCustomers = csCustomerMapper.selectCsCustomerList(csCustomer);
        if (ObjectUtils.isNotEmpty(csCustomers)) {
            return csCustomers.get(0);
        }
        return null;
    }

    /**
     * 用客户名称找，因为中国公司全称不可以雷同
     */
    public CsCustomer getByCompanyName(String companyName) {
        CsCustomer csCustomer = new CsCustomer();
        csCustomer.setCompanyName(companyName);
        List<CsCustomer> csCustomers = csCustomerMapper.selectCsCustomerList(csCustomer);
        if (ObjectUtils.isNotEmpty(csCustomers)) {
            return csCustomers.get(0);
        }
        return null;
    }



    /**
     * 新增客户
     * 快速插入
     * @param csCustomer 客户
     * @return 结果
     */
    public int fastInsertCsCustomer(CsCustomer csCustomer) {
        String code = "ZJCS"+DateUtils.getTimestampNow();
        csCustomer.setCompanyCode(code);
        csCustomer.setCreateBy(SecurityUtils.getLoginUserIdTypeString());
        return csCustomerMapper.insertCsCustomer(csCustomer);
    }




}
